#include <iostream>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "commen.h"

bool makeFifo()
{
    int n = mkfifo(FILENAME, 0666);
    if(n < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        return false;
    }
    return true;
}

int main()
{
    int rfd = open(FILENAME, O_RDONLY); //若管道不存在，则打开失败
    while(rfd < 0)
    {
        bool ret = makeFifo(); //创建管道
        if(ret == false) 
        {
            std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
            return 1;
        }
        rfd = open(FILENAME, O_RDONLY); //再次尝试打开
    }
    char buffer[1024];
    while(true)
    {
        ssize_t s = read(rfd, buffer, sizeof(buffer)-1);
        if(s > 0)
        {
            buffer[s] = '\0'; 
            std::cout << "client say: " << buffer << std::endl;  
        }
    }
    close(rfd);
    return 0;
}